﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using TappUpsRefresh.Extras;
using SlXnaApp3;
using System.IO;
using System.Windows.Media.Imaging;
using System.Threading;
using Microsoft.Xna.Framework;

namespace temp
{ 
    public partial class MainPage : PhoneApplicationPage
    {
        [Obsolete("Fuck OFF! :P")]
        DefaultInfo info { get; set; }
        Profile profile { get; set; }
        Thread progressBarThread;
        // Constructor
        public MainPage()
        {
            info = DefaultInfo.Retrieve(); 
            InitializeComponent();            
            progressBarThread = new Thread(() =>
            {
                //LoadingProgress();
            });
            
            LoadingProgress();
            progressBarThread.IsBackground = true;
            progressBarThread.Start();
            pb1.Visibility = System.Windows.Visibility.Visible;
            ptb1.Visibility = System.Windows.Visibility.Visible;
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            new Game().Exit();
            base.OnBackKeyPress(e);
        }

        private void LoadingProgress()
        {

            #region Last Error Prone Content
            try
            {
                WebClient web = new WebClient();
                web.BaseAddress = @"http://rushabh.greenpoison.org.in/countries";
                web.DownloadStringCompleted += new DownloadStringCompletedEventHandler(web_DownloadStringCompleted);
                web.DownloadStringAsync(new Uri(@"http://rushabh.greenpoison.org.in/countries"));
                SettingsClass settings = SettingsClass.Retrieve();
                EasyModeSw.IsChecked = settings.easyMode;
                mute.IsChecked = settings.mute;

                
            }
            catch (NullReferenceException e)
            {

            }
            catch (WebException _e)
            {

            }
            try
            {
                profile = Profile.Retrieve();
                datePicker1.Value = profile.BirthDate;
                name1.Text = profile.Name;
            }
            catch (NullReferenceException e)
            {

            }

            try
            {
                System.IO.IsolatedStorage.IsolatedStorageFile isf = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
                var temp = isf.GetFileNames();
                System.IO.IsolatedStorage.IsolatedStorageFileStream isfs = new System.IO.IsolatedStorage.IsolatedStorageFileStream(profile.Name + ".jpg", FileMode.OpenOrCreate, isf);
                BitmapImage img = new BitmapImage();
                MemoryStream ms = new MemoryStream();
                isfs.CopyTo(ms);
                img.SetSource(ms);
                UserImage.Source = img;
            }
            catch (Exception e)
            { }

            try
            {
                proileExplorer.ItemsSource = Profile.ItemsSource();
            }
            catch (Exception e)
            { }
            #endregion
            //pb.Visibility = System.Windows.Visibility.Collapsed;
            //ptb1.Visibility = System.Windows.Visibility.Collapsed;
        }


        void web_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                String s = e.Result;
                if (s.Contains("<p>Afghanistan"))
                {
                    int p = s.IndexOf("<p>Afghanistan");
                    int q = s.IndexOf("Zimbabwe</p>");
                    String temp = null;
                    for (int i = p + 3; i < q - 3; i++)
                    {
                        temp += s[i];
                    }

                    countryList.ItemsSource = temp.Split(' ').ToList();
                    countryList.SelectedItem = profile.Country.ToString();
                }
            }
            catch (Exception e1)
            {
                try
                {
                    countryList.Items.Add(profile.Country);
                    countryList.SelectedItem = profile.Country.ToString();


                    pb1.Visibility = System.Windows.Visibility.Collapsed;
                    ptb1.Visibility = System.Windows.Visibility.Collapsed;    
                }
                catch (Exception e2)
                { }
            }

            pb1.Visibility = System.Windows.Visibility.Collapsed;
            ptb1.Visibility = System.Windows.Visibility.Collapsed;   
        }

        // Simple button Click event handler to take us to the second page
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/GamePage.xaml", UriKind.Relative));
        }

        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri(@"/LevelSelector.xaml", UriKind.RelativeOrAbsolute));
        }

        private void Button_Click_4(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri(@"/Rules.xaml", UriKind.RelativeOrAbsolute));
        }

        private void ToggleSwitch_Checked(object sender, RoutedEventArgs e)
        {
            SettingsClass settings = new SettingsClass();
            settings.easyMode = EasyModeSw.IsChecked.Value;
            settings.score = true;
            settings.mute = mute.IsChecked.Value;
            settings.ShowJoyStick = !control.IsChecked.Value;
            //if (mute.IsChecked.Value)
            //    volume.IsEnabled = false;
            //else
            //    volume.IsEnabled = true;
            //settings.Volume = volume.Value;
            SettingsClass.Save(settings);
        }

        private void Pivot_Loaded(object sender, RoutedEventArgs e)
        {
            //WebClient d = new WebClient();
            //d.OpenReadCompleted += new OpenReadCompletedEventHandler(d_OpenReadCompleted);
            //d.OpenReadAsync(new Uri(@"http://avatar.xboxlive.com/avatar/" + "rushabhgosar" + "/avatar-body.png"));
            
        }      

        void d_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            //try
            //{
            //    MemoryStream ms = new MemoryStream();
            //    e.Result.CopyTo(ms);
            //    BitmapImage img = new BitmapImage();
            //    img.SetSource(ms);
            //    Image1.Source = img;
            //}
            //catch (WebException _e)
            //{
            //    MessageBox.Show("No Internet! :(");
            //}
        }

        private void Button_Click_5(object sender, RoutedEventArgs e)
        {
            Microsoft.Phone.Tasks.PhotoChooserTask a = new Microsoft.Phone.Tasks.PhotoChooserTask();
            a.Completed += new EventHandler<Microsoft.Phone.Tasks.PhotoResult>(a_Completed);
            a.Show();
        }

        void a_Completed(object sender, Microsoft.Phone.Tasks.PhotoResult e)
        {
            try
            {
                if (e.TaskResult == Microsoft.Phone.Tasks.TaskResult.OK)
                {
                    MemoryStream ms = new MemoryStream();
                    BitmapImage img = new BitmapImage();
                    e.ChosenPhoto.CopyTo(ms);
                    MemoryStream ms2 = new MemoryStream(ms.GetBuffer());
                    img.SetSource(ms);
                    System.IO.IsolatedStorage.IsolatedStorageFile isf = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();

                    System.IO.IsolatedStorage.IsolatedStorageFileStream isfs = new System.IO.IsolatedStorage.IsolatedStorageFileStream("/Photo.jpg", FileMode.OpenOrCreate, isf);
                    ms2.CopyTo(isfs);
                    UserImage.Source = img;
                    isfs.Close();
                }
                if (e.TaskResult == Microsoft.Phone.Tasks.TaskResult.Cancel)
                {

                }
            }
            catch (Exception _e)
            { }
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            if (name1.Text.Trim() == String.Empty || datePicker1.Value == null)
            {
                MessageBox.Show("You have not entered the minimum amout of details");
                return;
            }
            Profile profile = new Profile();
            profile.Name = name1.Text;
            //profile.Country = countryList.SelectedItem.ToString();
            profile.Score = 0;
            profile.BirthDate = datePicker1.Value.Value;
            profile.Difficulty = EasyModeSw.IsChecked.Value ? "Easy" : "Difficult";
            Profile.Save(profile);
            if (info == null)
                info = new DefaultInfo();
            info.profileName = profile.Name;

        }
        private void Button_Click_7(object sender, RoutedEventArgs e)
        {

            try
            {
                if (info == null)
                    info = new DefaultInfo();
                info.profileName = proileExplorer.SelectedItem.ToString();
                DefaultInfo.Save(info);
                Profile pro = Profile.Retrieve();
                name1.Text = pro.Name;
                profile.ImageName = pro.ImageName;
                countryList.SelectedItem = pro.Country;                
                datePicker1.Value = pro.BirthDate;
                MessageBox.Show("Load Complete!");
                System.IO.IsolatedStorage.IsolatedStorageFile isf = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
                System.IO.IsolatedStorage.IsolatedStorageFileStream isfs = new System.IO.IsolatedStorage.IsolatedStorageFileStream(profile.ImageName, FileMode.OpenOrCreate, isf);
                BitmapImage img = new BitmapImage();
                MemoryStream ms = new MemoryStream();
                isfs.CopyTo(ms);
                img.SetSource(ms);
                UserImage.Source = img;

            }
            catch (Exception e1)
            {
                MessageBox.Show("Invalid Operation \nError =" + e1.Message);
            }
        }

        private void hyp1_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Phone.Tasks.WebBrowserTask web = new Microsoft.Phone.Tasks.WebBrowserTask();
            web.URL = @"http://rushabh.greenpoison.org.in/blog/2012/03/06/tappups/";
            web.Show();
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            Microsoft.Phone.Tasks.EmailComposeTask email = new Microsoft.Phone.Tasks.EmailComposeTask();
            email.To = @"rushabh.techie@gmail.com";
            email.Subject = @"Feedback TappUp";
            email.Show();
        }

        private void volume_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {

        }

        private void Button_Click_6(object sender, RoutedEventArgs e)
        {

        }
    }
}